package org.shreker.tools.utils.json;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import org.shreker.tools.utils.time.DateTimeUtil;

import java.text.SimpleDateFormat;

public class JSONUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        //对象的所有字段全部列入
        objectMapper.setSerializationInclusion(Inclusion.NON_NULL);

        //取消默认转换timestamps形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

        //忽略空Bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

        /////////////////////////////  反序列化配置  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\

        //所有的日期格式都统一为以下的样式，即yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

        //忽略 在json字符串中存在，但是在java对象中不存在对应属性的情况。防止错误
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    /////////////////////////////  序列化配置  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\

    public static <T> String parseObject(T obj) throws RuntimeException {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("Parse Object to String error", e);
        }
    }

    public static <T> String parseObjectPretty(T object) throws RuntimeException {
        if (object == null) {
            return null;
        }
        try {
            return object instanceof String ? (String) object : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException("Parse Object to String error", e);
        }
    }

    public static <T> T formatObject(String source, Class<T> clazz) throws RuntimeException {
        if (StringUtils.isEmpty(source) || clazz == null) {
            return null;
        }
        try {
            return clazz.equals(String.class) ? (T) source : objectMapper.readValue(source, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Parse String to Object error", e);
        }
    }

    public static <T> T formatObject(String source, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(source) || typeReference == null) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? source : objectMapper.readValue(source, typeReference));
        } catch (Exception e) {
            throw new RuntimeException("Parse String to Object error", e);
        }
    }

    public static <T> T formatObject(String str, Class<?> collectionClass, Class<?>... elementClasses) throws RuntimeException {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
        try {
            return objectMapper.readValue(str, javaType);
        } catch (Exception e) {
            throw new RuntimeException("Parse String to Object error", e);
        }
    }

    //public static void main(String[] args) {
    //    TestPojo testPojo = new TestPojo();
    //    testPojo.setName("shreker");
    //    testPojo.setId(666);
    //
    //    //{"name":"shreker","id":666}
    //    String json = "{\"name\":\"shreker\",\"color\":\"blue\",\"id\":666}";
    //    TestPojo testPojoObject = JSONUtil.string2Obj(json, TestPojo.class);
    //    //        String testPojoJson = JSONUtil.obj2String(testPojo);
    //    //        log.info("testPojoJson:{}",testPojoJson);
    //
    //    log.info("end");
    //
    //    //User user = new User();
    //    //user.setId(2);
    //    //user.setEmail("shreker@shreker.com");
    //    //user.setCreateTime(new Date());
    //    //String userJsonPretty = JSONUtil.obj2StringPretty(user);
    //    //log.info("userJson:{}",userJsonPretty);
    //
    //
    //    //User u2 = new User();
    //    //u2.setId(2);
    //    //u2.setEmail("shrekeru2@shreker.com");
    //
    //    //String user1Json = JSONUtil.obj2String(u1);
    //    //
    //    //String user1JsonPretty = JSONUtil.obj2StringPretty(u1);
    //    //
    //    //log.info("user1Json:{}",user1Json);
    //    //
    //    //log.info("user1JsonPretty:{}",user1JsonPretty);
    //    //
    //    //User user = JSONUtil.string2Obj(user1Json,User.class);
    //    //
    //    //List<User> userList = Lists.newArrayList();
    //    //userList.add(u1);
    //    //userList.add(u2);
    //    //
    //    //String userListStr = JSONUtil.obj2StringPretty(userList);
    //    //
    //    //log.info("==================");
    //    //
    //    //log.info(userListStr);
    //    //
    //    //List<User> userListObj1 = JSONUtil.string2Obj(userListStr, new TypeReference<List<User>>() {});
    //    //
    //    //List<User> userListObj2 = JSONUtil.string2Obj(userListStr,List.class,User.class);
    //
    //    System.out.println("end");
    //
    //}


}
